//
//  QDataUtility.m
//  QoilPublic
//
//  Created by zhuang on 16/7/11.
//  Copyright © 2016年 杨凯. All rights reserved.
//

#import "QDataUtility.h"
#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApiObject.h"
#import "WXApi.h"
#import "QNavigationVC.h"
#import "QPaySuccessVC.h"
// 存储
#define LoginModelFile [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"login.data"]
@implementation QDataUtility


#pragma mark - LoginModel
//存
+ (void)updateLoginModel:(QLoginModel *)loginModel{
    [NSKeyedArchiver archiveRootObject:loginModel toFile:LoginModelFile];
    [QUserInfo sharedInfo].loginModel = loginModel;
}

//取
+ (QLoginModel *)getLoginModel{
    return [NSKeyedUnarchiver unarchiveObjectWithFile:LoginModelFile];
}

//删
+ (void)deleteLoginModel{
    QLoginModel *loginModel = [NSKeyedUnarchiver unarchiveObjectWithFile:LoginModelFile];
    if(loginModel){
        NSFileManager *defalutManager = [NSFileManager defaultManager];
        if([defalutManager isDeletableFileAtPath:LoginModelFile]){
            [defalutManager removeItemAtPath:LoginModelFile error:nil];
        }
    }
    [QDataUtility deleteAllArchive];//清除所以缓存
    if([QUserInfo sharedInfo].loginModel){
        [QUserInfo sharedInfo].loginModel = nil;
    }
}

+ (void)deleteAllArchive {
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    if ([defaultManager isDeletableFileAtPath:LoginModelFile]) {
        [defaultManager removeItemAtPath:LoginModelFile error:nil];
    }
}

//支付宝支付
+ (void)gotoAliPayWithData:(id)data{
    
//    if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipay:"]]) {
//        //如果没有安装支付宝客户端那么需要安装
//        [QViewUtility showToastToView:[UIApplication sharedApplication].keyWindow message:@"您还未安装支付宝客户端"];
//        return;
//    }

    NSDictionary *dict = (NSDictionary *)data;
    NSString *partner = dict[@"partner"];
    NSString *seller = dict[@"seller_id"];
    NSString *sign = dict[@"sign"];  // 私钥应保存在服务端？？
    
    //partner和seller获取失败,提示
    	if ([partner length] == 0 ||
            [seller length] == 0 ||
            [sign length] == 0)
    	{
    		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
    														message:@"缺少partner或者seller或者私钥。"
    													   delegate:self
    											  cancelButtonTitle:@"确定"
    											  otherButtonTitles:nil];
    		[alert show];
    		return;
    	}
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.sellerID = seller;
    order.outTradeNO = dict[@"out_trade_no"]; //订单ID（
    order.subject = dict[@"subject"]; //商品标题
    order.body = dict[@"body"]; //商品描述
    order.totalFee = dict[@"total_fee"];//商品价格
    order.notifyURL =  dict[@"notify_url"]; //回调URL
    order.service = dict[@"service"];
    order.paymentType = @"1";
    order.inputCharset = dict[@"_input_charset"];
    order.itBPay = dict[@"it_b_pay"];
    //order.showURL = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"OilAliPay";//传*************************************
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
   // NSLog(@"orderSpec = %@",orderSpec);
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
//    id<DataSigner> signer = CreateRSADataSigner(privateKey);
//    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (sign != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, sign, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            CLog(@"reslut = %@",resultDic);
            
            NSNumber *num = resultDic[@"resultStatus"];
            if(num.integerValue == 9000){//支付成功
                if([[QUserInfo sharedInfo].payTypeStr isEqualToString:paytopup]){//充值**********
                    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTopUpMoneySuccess object:nil];
                    QLoginModel *logModel = [QUserInfo sharedInfo].loginModel;
                    logModel.level = @"1";
                    [QDataUtility updateLoginModel:logModel];
                }else if ([[QUserInfo sharedInfo].payTypeStr isEqualToString:payorder]){//支付订单
                    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
                    if ([keyWindow.rootViewController isKindOfClass:[QNavigationVC class]]){
                        QNavigationVC *nav = (QNavigationVC *)keyWindow.rootViewController;
                        QPaySuccessVC *vc = [[QPaySuccessVC alloc] init];
                        [nav pushViewController:vc animated:YES];
                    }
                }
            }
        }];
    }
}

//微信支付
+ (void)gotoWeChatPay:(id)data{

//    NSDictionary *dic = (NSDictionary *)data;
//    payRequsestHandler *req = [payRequsestHandler alloc];
//    //初始化支付签名对象
//    [req init:dic[@"appid"] mch_id:dic[@"partnerid"]];
//    //设置密钥
//    [req setKey:dic[@"sign"]];
//    //获取到实际调起微信支付的参数后，在app端调起支付
//    NSMutableDictionary *dict = [req sendPay_demoWithData:data];
    
    if(![WXApi isWXAppInstalled]){
        
        [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"您还未安装微信客户端" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];

        return;
    }

    NSDictionary *dict = (NSDictionary *)data;
    if ( dict != nil) {
        if(dict != nil){
            NSMutableString *retcode = [dict objectForKey:@"retcode"];
            if (retcode.intValue == 0){
                NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
                
                //调起微信支付
                PayReq* req             = [[PayReq alloc] init];
                req.partnerId           = [dict objectForKey:@"partnerid"];
                req.prepayId            = [dict objectForKey:@"prepayid"];
                req.nonceStr            = [dict objectForKey:@"noncestr"];
                req.timeStamp           = stamp.intValue;
                req.package             = [dict objectForKey:@"packageValue"];
                req.sign                = [dict objectForKey:@"sign"];
                
                [WXApi sendReq:req];
                //日志输出
                NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",[dict objectForKey:@"appid"],req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
                //return @"支付结果";
            }else{
                //return [dict objectForKey:@"retmsg"];
            }
        }else{
            //return @"服务器返回错误，未获取到json对象";
        }
    }else{
       // return @"服务器返回错误";
    }
}

@end
